//
//  CHSetExtensions.m
//  Chocolat
//
//  Created by Pieter Omvlee on 5/30/08.
//  Copyright 2008 Bohemian Coding. All rights reserved.
//

#import "CHSetExtensions.h"

@implementation NSSet (CHSetExtensions)

- (BOOL)containsObjectFromArray:(NSArray *)anArray
{
  for (id obj in anArray)
    if ([self containsObject:obj])
      return YES;
  
  return NO;
}

- (NSSet *)map:(SEL)sel
{
  return [self map:sel withObject:nil];
}

- (NSSet *)map:(SEL)sel withObject:(id)obj
{
  return [self map:sel withObject:obj withObject:nil];
}

- (NSSet *)map:(SEL)sel withObject:(id)obj1 withObject:(id)obj2
{
  NSMutableSet *result = [NSMutableSet set];
  for (id elem in self)
    [result addObject:[elem performSelector:sel withObject:obj1 withObject:obj2]];
  return result;
}

- (NSSet *)setByRemovingObject:(id)anObject
{
  NSMutableSet *cpy = [[self mutableCopy] autorelease];
  [cpy removeObject:anObject];
  return cpy;
}

+ (NSSet *)setByMergingSetsInArray:(NSArray *)anArray
{
  NSMutableSet *result = [NSMutableSet set];
  for (NSSet *s in anArray)
    [result addObjectsFromArray:[s allObjects]];
  
  return result;
}

+ (NSSet *)setByMergingSet:(NSSet *)set1 andSet:(NSSet *)set2
{
  return [self setByMergingSetsInArray:[NSArray arrayWithObjects:set1,set2,nil]];
}

+ (NSSet *)setByMergingArraysInArray:(NSArray *)anArray
{
  NSMutableArray *array = [NSMutableArray array];
  for (NSArray *arr in anArray)
    [array addObject:[NSSet setWithArray:arr]];
  
  return [self setByMergingSetsInArray:array];
}

+ (NSSet *)setByMergingArray:(NSArray *)array1 andArray:(NSArray *)array2
{
  return [self setByMergingArraysInArray:[NSArray arrayWithObjects:array1,array2, nil]];
}

@end

@implementation NSSet (NSSetAdditions)

- (id)deepCopy {
  return [NSSet setWithArray:[[self allObjects] mutableDeepCopy]];
}

- (id)mutableDeepCopy {
  return [NSMutableSet setWithArray:[[self allObjects] mutableDeepCopy]];
}

@end

@implementation NSDictionary (NSDictionaryAdditions)

- (id)deepCopy {
  return [NSDictionary dictionaryWithDictionary:[self mutableDeepCopy]];
}

- (id)mutableDeepCopy {
  return [NSMutableDictionary dictionaryWithObjects:[[self allValues] deepCopy]
                                            forKeys:[self allKeys]];
}

@end

@implementation NSMutableSet (NSMutableSetAdditions)
- (void)addObjectIfNotNil:(id)anObject
{
  if (anObject)
    [self addObject:anObject];
}
@end
